package com.seed.service.sysmanager;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.seed.commons.dbutil.DB;
import com.seed.commons.util.BaseUtil;
import com.seed.commons.util.RandomUtil;

/**
 * @标题：解析菜单XML文档获得数据持久化到DB
 * @描述：
 * @编写者：杨浩泉
 * @日期：2012-2-10<b>下午10:03:56</b>
 */
public class ParseMenuXmlToDB {

	private static final String xml_root_path = BaseUtil.getProjectPath() + "/WebRoot/WEB-INF/xml_menu/";

	private Log log = LogFactory.getLog(getClass()) ;
	
	public ParseMenuXmlToDB() {
		new ClassPathXmlApplicationContext("config/bean.xml") ;
	}
	
	/**
	 * 解析MenuItem_.xml持久到DB
	 */
	@SuppressWarnings("unchecked")
	public void parseMenuItem() {
		String sql = "INSERT INTO SEED_MENU_ITEM(MLId,MLName,MLIsRoot,MLUrl,MLDesc,MLIcon,MLFunbar,SEED_MENU_MODEL_MMId_FK,SEED_MENU_ITEM_MLId_FK) VALUES(?,?,?,?,?,?,?,?,?)" ;
		
		String rootName = "" ;
		String rootDesc = "" ;
		String rootId = "";
		String rootText = "";
		String rootIsroot = "";
		String rootFKId = "";
		String childText = "";
		String childUrl = "";
		String childIcon = "";
		String childDesc = "";
		StringBuffer funbarjson =  null ;
		
		Document docModel = BaseUtil.getDocument(xml_root_path + "MenuModel.xml");
		
		List<Element> menuItemsID = docModel.selectNodes("//MenuModel/item") ;
		
		for (Iterator<Element> iterator = menuItemsID.iterator(); iterator.hasNext();) {
			Element modelElement = (Element) iterator.next();
			String menuItemId = modelElement.attributeValue("id") ;
			
			//通过MenuModel的id来拼装MenuItem_文件名称
			Document docItem = BaseUtil.getDocument(xml_root_path + "MenuItem_"+menuItemId+".xml");
			if(null != docItem) {
				
				String itemRootId = RandomUtil.getRandomNum(5) ;
				
				Element rootElt = docItem.getRootElement() ;
				rootName = rootElt.attributeValue("name") ;
				rootDesc = rootElt.attributeValue("desc") ;
				System.out.println(rootDesc);
				
				try {
					DB.insert(sql, new Object[]{itemRootId,rootName,null,null,rootDesc,null,null,menuItemId,null}) ;
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				List<Element> items = rootElt.elements() ;
				
				for (Iterator<Element> it = items.iterator(); it.hasNext();) {
					Element itemroot = (Element) it.next();
					
					rootId = itemroot.attributeValue("id") ;
					rootText = itemroot.attributeValue("text") ;
					rootIsroot = itemroot.attributeValue("isroot") ;
					rootFKId = itemroot.attributeValue("fkid") ;
					
					System.out.println("\r\n" + rootId + "\t" + rootText + "\t" + rootIsroot) ;
					
					String itemId = RandomUtil.getRandomNum(5) ;
					try {
						DB.insert(sql, new Object[]{itemId,rootText,rootIsroot,null,rootDesc,null,null,rootFKId,itemRootId}) ;
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					List<Element> itemChild = itemroot.elements() ;
					for (Iterator<Element> iter = itemChild.iterator(); iter.hasNext();) {
						Element child = (Element) iter.next();
						childText = child.attributeValue("text") ;
						
						List<Element> userdataElt = child.elements() ;
						for (Iterator<Element> iterator2 = userdataElt.iterator(); iterator2.hasNext();) {
							Element userdata = (Element) iterator2.next();
							String name = userdata.attributeValue("name") ;
							
							if("url".equals(name))
								childUrl = userdata.getTextTrim() ;
							if("icon".equals(name))
								childIcon = userdata.getTextTrim() ;
							if("desc".equals(name))
								childDesc = userdata.getTextTrim() ;
							if("funbar".equals(name)) {
								funbarjson = new StringBuffer() ;
								List<Element> funbar = userdata.elements() ;
								
								funbarjson.append("[") ;
								for (Iterator<Element> iterator3 = funbar.iterator(); iterator3.hasNext();) {
									Element fb = (Element) iterator3.next();
									funbarjson.append("{")
									.append("name:").append("\""+fb.attributeValue("name")+"\"")
									.append(",")
									.append("url:").append("\""+fb.attributeValue("url")+"\"")
									.append(",");
									funbarjson.deleteCharAt(funbarjson.length() -1) ;
									funbarjson.append("}");
									funbarjson .append(",");
								}
								funbarjson.deleteCharAt(funbarjson.length() -1) ;
								funbarjson.append("]") ;
							}
						}
						try {
							DB.insert(sql, new Object[]{RandomUtil.getRandomNum(5),childText,"N",childUrl,childDesc,childIcon,(null == funbarjson?null:funbarjson.toString()),null,itemId}) ;
						} catch (Exception e) {
							e.printStackTrace();
						}
						System.out.println(childText +"\t"+ childUrl + "\t" + (null == funbarjson?null:funbarjson.toString()));
						funbarjson = null ;
					}
					
				}
			}
		}
	}
	
	
	
	/**
	 * 解析MenuModel.xml持久到DB
	 */
	@SuppressWarnings("unchecked")
	public void parseMenuModel() {
		String sql = "INSERT INTO SEED_MENU_MODEL(MMId,MMName,MMUrl,MMDesc,Sort) VALUES(?,?,?,?,?)" ;

		Document document = BaseUtil.getDocument(xml_root_path + "MenuModel.xml");

		Element root = document.getRootElement();

		for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {
			Element element = (Element) i.next();
			
			String id = element.attributeValue("id") ;
			String text = element.attributeValue("text") ;
			String url = "" ;
			String sort = "" ;
			String desc = "" ;
			
			List<Element> list = element.elements() ;
			
			for (Iterator<Element> iterator = list.iterator(); iterator.hasNext();) {
				Element elitem = (Element) iterator.next();
				String name = elitem.attributeValue("name") ;
				if("url".equals(name))
					url = elitem.getTextTrim() ;
				if("sort".equals(name))
					sort = elitem.getTextTrim() ;
				if("desc".equals(name))
					desc = elitem.getTextTrim() ;
			}
			
			try {
				DB.insert(sql, new Object[]{id,text,url,desc,sort}) ;
				log.info("执行SQL:" + sql) ;
			} catch (Exception e) {
				e.printStackTrace();
				log.info("\r\n解析MenuMode.xml文档获得数据，持久化到数据库错误！" + e.getMessage()) ;
			}
		}

	}

	public static void main(String[] args) {
		new ParseMenuXmlToDB().parseMenuModel();
		new ParseMenuXmlToDB().parseMenuItem();
	}
}
